#!/usr/bin/perl -w
use 5.010;
use strict;
use warnings;
use Getopt::Long;

use FindBin qw($Bin);
use lib "$Bin";

use CONFIG::ServConfig;
use CONFIG::CommandParser;
use Common::APPComm;
use File::Stamped;

my $LOGFILE="$Bin/SNMP_VAL_CMD.log";

my $fh = File::Stamped->new(pattern=>$LOGFILE);
local $Log::Minimal::PRINT = sub {
  my($time,$type,$message,$trace) = @_;
  print {$fh}"$time [$type] $message at $trace\n";
};

my $optType="get";
my $devid=0;
my $miboid="";
my $val;
my ($RESULT_STS,$ERROR_MSG,$RESULT_VAL)=("NG","","[]");


GetOptions(
           "opt|o=s"=>\$optType,
           "device=i"=>\$devid,
           "mib=s"=>\$miboid,
           "val=s"=>\$val);


#print "optType=$optType,devid=$devid,mibid=$mibid,val=$val.\n";



my $configFile ="$Bin/snmpserver.config";
my $configHandler = CONFIG::ServConfig->new($configFile);
my $commandParser = CONFIG::CommandParser->new($configHandler);

if (!defined $configHandler) {
    $ERROR_MSG="Can't open application ConfigFile.";
    print &GetRet();
    return;
}


my $parserCmd = $optType." device=".$devid." mib=".$miboid;
$parserCmd.=" val=".$val if defined($val);
#print $parserCmd;

my $retVal = $commandParser->ParseCommand($parserCmd);

if ($retVal->{"RETCODE"}!=$Common::APPComm::RESULT_OK) {
    $ERROR_MSG=$Common::APPComm::ERRORHANDLER->{$retVal->{"RETCODE"}};
    print &GetRet();
}else{
    $RESULT_STS="OK";
    $ERROR_MSG=$Common::APPComm::ERRORHANDLER->{$retVal->{"RETCODE"}};
    my $mibInform=$retVal->{"MIBINFOM"};
    if ($mibInform->{"GET_MIB_OID"}) {
        $RESULT_VAL="[".$mibInform->{"GET_MIB_OID"} . ":" . $mibInform->{"MIB_DATATYPE"} . ":" . $mibInform->{"GET_MIB_OID_VAL"} . "]";
    }elsif($mibInform->{"GET_MIB_TABLE"}) {
         my $tableData = $mibInform->{"GET_MIB_TABLE"};
          for my $oidKey (sort keys %$tableData) {
            $RESULT_VAL.="[". $oidKey . ":" . $mibInform->{"MIB_DATATYPE"} . ":" . $tableData->{$oidKey} . "]";
          }
    }
    print &GetRet();
}


#printf("RESULT:NG;ERROR:'XXXX';RESULT_VAL:[.1.3.6.1.2.1.1.5.0:OCTET_STRING:OSRCAD]");
sub GetRet {
    return "RETURN:$RESULT_STS;ERROR:$ERROR_MSG\n";
}
